package com.fingard.dsp.bank.directbank.cmb01;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CMB01Receipt extends CMB01Base implements IReceipt {
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        if("0".equals(getBankConfig().getValueAsString("receiptQySyncTaskFlag"))){
            //电子回单查询返回ATS的对象
            RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
            String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
            if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                        CMB01SyncTask tmpTask = new CMB01SyncTask(p_reqReceipt);
                        tmpTask.bankFront = this.bankFront;
                        tmpTask.reqHeader = this.reqHeader;
                        tmpTask.downloadReceipt();
                        retAts.respCode = "0";
                        retAts.respInfo = "后台处理中";
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件共享目录";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
            }
            retAts.writeRetToATS();
            return retAts;
        }else {
            RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);

            try {
                Calendar tmpCalendarFrom = Calendar.getInstance();
                tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

                Calendar tmpCalendarTo = Calendar.getInstance();
                tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

                int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

                //按日循环
                String printFlagStr = getValueAsString("printFlag");
                if (StringHelper.isNullOrEmpty(printFlagStr)) {
                    WriteBankLogLn2("配置文件缺失招行回单打印标志配置（1:未打印，2:已打印）:<printFlag></printFlag>，当前使用默认值1。");
                    printFlagStr = "1";
                }
                String[] printFlags = printFlagStr.split(",");
                DataFileHelper dFileHelper = new DataFileHelper(this);
                while (tmpIntFrom <= tmpIntTo) {//按日查询

                    for (String printFlag : printFlags) {
                        try {
                            printFlag = printFlag.trim();
                            if (!"1".equals(printFlag) && !"2".equals(printFlag)) {
                                WriteBankLogLn("配置文件招行回单打印标志配置不规范：" + printFlag);
                                continue;
                            }
                            boolean hasCacheData = false;
                            Date dateNow = new Date();
                            int intToday = Integer.parseInt(Format.Date8Format.format(dateNow));

                            int intFromStep = tmpIntFrom;
                            Date fromDateStep = tmpCalendarFrom.getTime();

                            String dataFilePath = dFileHelper.getBankReceiptDataFile(fromDateStep, printFlag + "_" + p_reqReceipt.actNum);
                            File dataFile = new File(dataFilePath);
                            if (dataFile.exists()) {
                                this.WriteBankLogLn(intFromStep + "的回单已执行过下载，如需重新获取，请删除文件" + dataFilePath);
                                retAts.respCode = "0";
                                retAts.respInfo = intFromStep + "的回单已执行过下载";
                                continue;
                            }


                            WriteBankLogLn("执行" + intFromStep + "的回单数据查询");
                            //第一步查回单数据
                            CMB01Header tmpBnkHeader = new CMB01Header();
                            tmpBnkHeader.FUNNAM = "SDKCSFDFBRT";

                            XmlTextWriter xmlWriter = new XmlTextWriter();
                            xmlWriter.autoFormat = false;
                            writeCommonHeader(xmlWriter, tmpBnkHeader);

                            xmlWriter.writeStartElement("CSRRCFDFY0");
                            xmlWriter.writeElementString("EACNBR", p_reqReceipt.actNum); /* 账号 */
                            xmlWriter.writeElementString("BEGDAT", "" + intFromStep); /* 开始日期 */
                            xmlWriter.writeElementString("ENDDAT", "" + intFromStep); /* 结束日期 */
                            xmlWriter.writeElementString("RRCFLG", printFlag); /* 打印标志 */
                            xmlWriter.writeElementClosed("BEGAMT"); /* 最小金额 */
                            xmlWriter.writeElementClosed("ENDAMT"); /* 最大金额 */
                            xmlWriter.writeElementClosed("RRCCOD"); /* 回单代码 */
                            xmlWriter.writeEndElement();
                            xmlWriter.writeEndDocument();

                            String[] tmpStrRet1 = sendToBank(xmlWriter.toXmlString());
                            //测试用
                            //tmpStrRet1[0] = "";
                            //tmpStrRet1[1] = FileHelper.readFileText("D:\\getToWork\\14-filesForDevelop\\CMB01\\电子回单\\step1.txt", "gbk");
                            //测试用
                            boolean doStep2 = false;
                            if (tmpStrRet1[0].length() == 0) {
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet1[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                                    String tmpERRMSG = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                    if ("0".equals(tmpRetCode)) {
                                        doStep2 = true;
                                        if (getBankConfig().getValueAsBool("alwaysCacheReceiptData")) {
                                            FileHelper.writeFile(dataFile, tmpStrRet1[1], FGBiz.dspCenter.charset);
                                            hasCacheData = true;
                                        }
                                    } else {
                                        WriteBankLogLn(tmpRetCode + "-" + tmpERRMSG);
                                    }
                                } else {
                                    WriteBankLogLn(tmpSbMsg);
                                }
                            } else {
                                WriteBankLogLn(tmpStrRet1[0] + "-" + tmpStrRet1[1]);
                            }
                            if (!doStep2) {
                                continue;
                            }
                            WriteBankLogLn("执行" + intFromStep + ("1".equals(printFlag) ? "未打印" : "已打印") + "的回单文件下载");


                            tmpBnkHeader = new CMB01Header();
                            tmpBnkHeader.FUNNAM = "SDKCSFDFBRTIMG";

                            xmlWriter = new XmlTextWriter();
                            xmlWriter.autoFormat = false;
                            writeCommonHeader(xmlWriter, tmpBnkHeader);

                            xmlWriter.writeStartElement("CSRRCFDFY0");
                            xmlWriter.writeElementString("EACNBR", p_reqReceipt.actNum); /* 账号 */
                            xmlWriter.writeElementString("BEGDAT", "" + intFromStep); /* 开始日期 */
                            xmlWriter.writeElementString("ENDDAT", "" + intFromStep); /* 结束日期 */


                            xmlWriter.writeElementString("RRCFLG", printFlag); /* 打印标志 */
                            xmlWriter.writeElementClosed("BEGAMT"); /* 最小金额 */
                            xmlWriter.writeElementClosed("ENDAMT"); /* 最大金额 */
                            xmlWriter.writeElementClosed("RRCCOD"); /* 回单代码 */
                            xmlWriter.writeEndElement();
                            xmlWriter.writeEndDocument();

                            String[] tmpStrRet2 = sendToBank(xmlWriter.toXmlString());
                            //测试用
                            //tmpStrRet2[0] = "";
                            //tmpStrRet2[1] = FileHelper.readFileText("D:\\getToWork\\14-filesForDevelop\\CMB01\\电子回单\\step2.txt", "gbk");
                            //测试用
                            if (tmpStrRet2[0].length() == 0) {
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet2[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                                    if ("0".equals(tmpRetCode)) {
                                        //下载成功之后，保存回单数据文件
                                        boolean saveCacheData = true;
                                        if (intFromStep < intToday) {
                                            double diffDays = DateHelper.getDifferDays(dateNow, fromDateStep);
                                            if (diffDays < 2) {//昨日需判断几时可以缓存
                                                int cacheHourSet = this.getBankConfig().getValueAsInt("receiptCacheHour");
                                                int stepHour = DateHelper.getHour(dateNow);
                                                if (stepHour < cacheHourSet) {
                                                    saveCacheData = false;
                                                    WriteBankLogLn("当天" + cacheHourSet + "时前不缓存昨日回单数据，保存为临时文件");

                                                }
                                            }
                                        } else {
                                            saveCacheData = false;
                                            WriteBankLogLn("当天不缓存回单数据，保存为临时文件");
                                        }
                                        if(!saveCacheData){
                                            if(dataFilePath.endsWith(".txt")){
                                                dataFilePath = dataFilePath.replace(".txt", ".tmp.txt");
                                            }else{
                                                dataFilePath += ".tmp";
                                            }
                                            WriteBankLogLn("临时文件路径："+dataFilePath);
                                            dataFile = new File(dataFilePath);
                                        }
                                        FileHelper.writeFile(dataFile, tmpStrRet1[1], FGBiz.dspCenter.charset);

                                        retAts.respCode = "0";
                                        retAts.respInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");

		                        /*
                                String tmpByDate = Format.Date8Format.format(new Date());
		                        tmpByDate = tmpByDate.substring(2, 6) + File.separator + tmpByDate.substring(6, 8);

		                        String receiptSaveToMainDir = getValueAsString("receiptSaveToMainDir");
		                        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
		                            String dataFilePath = receiptSaveToMainDir + File.separator + tmpByDate;
		                            retAts.dataFilePath = dataFilePath;

		                            File dataFile = new File(dataFilePath);
		                            if (!FileHelper.existFile(dataFilePath)) {
		                                dataFile.mkdirs();
		                            }

		                            String downloadReceiptDir = getValueAsString("downloadReceiptDir");
		                            if (!StringHelper.isNullOrEmpty(downloadReceiptDir)) {
		                                File receiptDir = new File(downloadReceiptDir);
		                                File[] receiptFiles = receiptDir.listFiles();
		                                int tmpFileCount = 0;
		                                for (File receiptFile : receiptFiles) {
		                                    String[] tmpNameSp = receiptFile.getName().split("_");
		                                    for (String tmpName : tmpNameSp) {
		                                        if (receiptFile.getAbsolutePath().endsWith(".jpg")) {
		                                            if (tmpNameSp.length == 3) {
		                                                tmpName = tmpNameSp[0] + "_" + tmpNameSp[2] + ".jpg";

		                                                File dspReceiptFile = new File(dataFilePath + File.separator + tmpName);
		                                                if (!dspReceiptFile.exists()) {
		                                                    dspReceiptFile.createNewFile();
		                                                }
		                                                copyFile(receiptFile.getAbsolutePath(), dspReceiptFile.getAbsolutePath());
		                                                tmpFileCount++;
		                                            } else {
		                                                retAts.respCode = "-1";
		                                                retAts.respInfo = "不符合回单文件名称命名规则!";
		                                            }
		                                        } else {
		                                            retAts.respCode = "-1";
		                                            retAts.respInfo = "招行电子回单图片格式非法!";
		                                        }
		                                    }
		                                }

		                                WriteBankLogLn2("共复制了" + tmpFileCount + "个文件!");
		                            } else {
		                                WriteBankLogLn2("配置文件缺失:<downloadReceiptDir></downloadReceiptDir>配置!");
		                            }
		                        } else {
		                            WriteBankLogLn2("配置文件缺失:<receiptSaveToMainDir></receiptSaveToMainDir>配置!");
		                        }
		                        */
                                    } else {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = tmpSbMsg.toString();
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpStrRet2[0] + tmpStrRet2[1];
                            }
                        } catch (Exception ex) {
                            WriteBankLogLn(ex);
                        }
                    }//是否打印

                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                }
            } catch (Exception ex) {
                ex.printStackTrace();

                retAts.respCode = "-1";
                retAts.respInfo = ex.getMessage();

                WriteBankLogLn(ex);
            }

            retAts.writeRetToATS();
            return retAts;
        }
    }
}
